package service

import (
	"fmt"
	"sysu-giep/internal/database/models"
	"time"

	"gorm.io/gorm"
)

type ApplicationService struct {
	db *gorm.DB
}

func NewApplicationService(db *gorm.DB) *ApplicationService {
	return &ApplicationService{
		db: db,
	}
}

// 获取申请列表
func (s *ApplicationService) GetApplications(page, size int, status string, projectID *uint, applicantID *uint) ([]models.Application, int64, error) {
	var applications []models.Application
	var total int64

	query := s.db.Model(&models.Application{})

	// 状态筛选
	if status != "" {
		query = query.Where("status = ?", status)
	}

	// 项目筛选
	if projectID != nil {
		query = query.Where("project_id = ?", *projectID)
	}

	// 申请人筛选
	if applicantID != nil {
		query = query.Where("applicant_id = ?", *applicantID)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * size
	if err := query.Preload("Project").
		Preload("Applicant").
		Preload("Reviewer").
		Order("created_at DESC").
		Offset(offset).
		Limit(size).
		Find(&applications).Error; err != nil {
		return nil, 0, err
	}

	return applications, total, nil
}

// 根据ID获取申请详情
func (s *ApplicationService) GetApplicationByID(id uint64) (*models.Application, error) {
	var application models.Application
	if err := s.db.Preload("Project").
		Preload("Applicant").
		Preload("Reviewer").
		First(&application, id).Error; err != nil {
		return nil, err
	}
	return &application, nil
}

// 创建申请
func (s *ApplicationService) CreateApplication(userID uint, req models.CreateApplicationRequest) error {
	// 检查项目是否存在
	var project models.Project
	if err := s.db.First(&project, req.ProjectID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("项目ID %d 不存在", req.ProjectID)
		}
		return err
	}

	// 检查项目状态是否开放
	if project.Status != models.ProjectStatusOpen {
		return fmt.Errorf("项目状态不是开放状态，无法申请")
	}

	// 检查项目是否公开
	if !project.IsPublic {
		return fmt.Errorf("项目不是公开状态，无法申请")
	}

	application := &models.Application{
		ProjectID:      req.ProjectID,
		ApplicantID:    userID,
		Status:         models.ApplicationStatusPending,
		CoverLetter:    req.CoverLetter,
		Resume:         req.Resume,
		Portfolio:      req.Portfolio,
		ResearchPlan:   req.ResearchPlan,
		Motivation:     req.Motivation,
		Qualifications: req.Qualifications,
		ExpectedTime:   req.ExpectedTime,
		StartDate:      req.StartDate,
		EndDate:        req.EndDate,
		ApplyDate:      time.Now(),
	}

	// 使用事务确保数据一致性
	err := s.db.Transaction(func(tx *gorm.DB) error {
		// 创建申请
		if err := tx.Create(application).Error; err != nil {
			return err
		}

		// 更新项目的申请人数
		if err := tx.Model(&project).UpdateColumn("apply_count", gorm.Expr("apply_count + ?", 1)).Error; err != nil {
			return err
		}

		return nil
	})

	return err
}

// 更新申请状态
func (s *ApplicationService) UpdateApplicationStatus(id uint64, userID uint, status models.ApplicationStatus, reviewerID *uint, reviewComment string) error {
	// 检查申请是否存在
	var application models.Application
	if err := s.db.Preload("Project").First(&application, id).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("申请ID %d 不存在", id)
		}
		return fmt.Errorf("查询申请失败: %v", err)
	}

	// 调试信息：记录关键数据
	fmt.Printf("DEBUG: 申请ID=%d, 申请人ID=%d, 课题创建者ID=%d, 当前用户ID=%d, 申请状态=%s\n",
		application.ID, application.ApplicantID, application.Project.CreatorID, userID, application.Status)

	// 检查权限：只有课题创建者可以审核申请
	if application.Project.CreatorID != userID {
		return fmt.Errorf("权限不足：当前用户ID(%d)不是课题创建者ID(%d)", userID, application.Project.CreatorID)
	}

	// 检查申请状态是否允许更新
	if application.Status != models.ApplicationStatusPending {
		return fmt.Errorf("申请状态错误：当前状态为%s，只能审核待审核状态的申请", application.Status)
	}

	// 更新申请状态和审核信息
	updates := map[string]interface{}{
		"status":         status,
		"reviewer_id":    reviewerID,
		"review_comment": reviewComment,
		"review_date":    time.Now(),
	}

	if err := s.db.Model(&models.Application{}).Where("id = ?", id).Updates(updates).Error; err != nil {
		return fmt.Errorf("更新申请状态失败: %v", err)
	}

	return nil
}

// 撤回申请
func (s *ApplicationService) WithdrawApplication(id uint64, userID uint) error {
	// id对应的申请是否属于userID用户
	var application models.Application
	if err := s.db.Model(&models.Application{}).Where("id = ? AND applicant_id = ?", id, userID).First(&application).Error; err != nil {
		return err // 无权撤回
	}

	return s.db.Model(&models.Application{}).Where("id = ?", id).Update("status", models.ApplicationStatusWithdrawn).Error
}

// 获取当前用户的申请
func (s *ApplicationService) GetMyApplications(page, size int, userID uint) ([]models.Application, int64, error) {
	var applications []models.Application
	var total int64

	query := s.db.Model(&models.Application{}).Where("applicant_id = ?", userID)

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * size
	if err := query.Preload("Project").
		Preload("Applicant").
		Preload("Reviewer").
		Order("created_at DESC").
		Offset(offset).
		Limit(size).
		Find(&applications).Error; err != nil {
		return nil, 0, err
	}

	return applications, total, nil
}

// 审核申请
func (s *ApplicationService) ReviewApplication(id uint64, reviewerID uint, status models.ApplicationStatus, reviewComment string) error {
	// 检查申请是否存在
	var application models.Application
	if err := s.db.First(&application, id).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("申请ID %d 不存在", id)
		}
		return err
	}

	// 更新申请状态和审核信息
	updates := map[string]interface{}{
		"status":         status,
		"reviewer_id":    reviewerID,
		"review_comment": reviewComment,
		"review_date":    time.Now(),
	}

	return s.db.Model(&models.Application{}).Where("id = ?", id).Updates(updates).Error
}
